package wqh.controller;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wqh.domain.Channel;
import wqh.domain.Device;
import wqh.domain.GeoBuilding;
import wqh.domain.MapPos;
import wqh.global.GlobalChannel;
import wqh.pojo.*;
import wqh.service.ChannelService;
import wqh.service.DeviceService;
import wqh.service.GeoBuildingService;
import wqh.service.MapPosService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/water/channel")
public class ChannelJSONController {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(ChannelJSONController.class);

    @Autowired
    private ChannelService channelService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private GeoBuildingService geoBuildingService;

    @Autowired
    private MapPosService mapPosService;

    @RequestMapping(value = "/get",method = RequestMethod.GET)
    public Object get(@RequestParam(value = "id",required = true) int id)
    {
      try{
          Channel channel = channelService.findByID(id);
          Device find = new Device();
          find.setDevice_name(channel.getName());
          find.setDevice_ip(channel.getIp());
          Device device = deviceService.findAllByNameAndIp(find);
          MapPos mapPos = new MapPos();
          mapPos.setDevice_id(device.getId());
          mapPos.setCh_x(channel.getChannel());
          mapPos.setGeo_building_id(channel.getGeo_id());
          List<MapPos> mapPosList = mapPosService.findRecordByClass(mapPos);
          Map<String,Object> map = new HashMap<String, Object>();
          map.put("geo_id",channel.getGeo_id());
          if(mapPosList.size() != 0){
              map.put("pos_x",mapPosList.get(0).getPos_x());
              map.put("pos_y",mapPosList.get(0).getPos_y());
              map.put("map_pos_id",mapPosList.get(0).getId());
          }
          return MapRet.DATA(map);
      }catch (Exception e){
          e.printStackTrace();
          return MapRet.ERROR();
      }
    }

    @RequestMapping(value = "/getSelect2DeviceName",method = RequestMethod.GET)
    public Object getSelect2DeviceName()
    {
        List<Device> deviceList = deviceService.findAllRecord();
        List<Select2DeviceName> select2DeviceNameList = new ArrayList<Select2DeviceName>();
        for(Device device : deviceList)
        {
            Select2DeviceName s = new Select2DeviceName(device.getId(),device.getDevice_name());
            select2DeviceNameList.add(s);
        }
        return select2DeviceNameList;
    }

    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    public Object getAll()
    {
        List<Channel> channelList = channelService.findAllRecord();
        List<ChannelCover> channelCoverList = new ArrayList<ChannelCover>();
        for(Channel channel : channelList){
            String geo = "无地理信息";
            if(channel.getGeo_id() != 0){
                GeoBuilding gA = geoBuildingService.findRecordById(channel.getGeo_id());
                if(gA == null) {
                    channelCoverList.add(new ChannelCover(channel,geo));
                    continue;
                }
                geo = gA.getName();
                if(gA.getLevel() == 2){
                    GeoBuilding gB = geoBuildingService.findRecordById(gA.getParent_id());
                    if(gB != null) {
                        geo = gB.getName() + "__" + geo;
                    }else{
                        channelCoverList.add(new ChannelCover(channel,geo));
                    }
                }
                if(gA.getLevel() == 3){
                    GeoBuilding gB = geoBuildingService.findRecordById(gA.getParent_id());
                    if(gB != null){
                        geo = gB.getName() + "__" + geo;
                        GeoBuilding gC = geoBuildingService.findRecordById(gB.getParent_id());
                        if(gC != null) {
                            geo = gC.getName() + "__" + geo;
                        }else{
                            channelCoverList.add(new ChannelCover(channel,geo));
                        }
                    }else{
                        channelCoverList.add(new ChannelCover(channel,geo));
                    }
                }
            }
            channelCoverList.add(new ChannelCover(channel,geo));
        }
        return MapRet.DATA(channelCoverList);
    }

    @RequestMapping(value = "/getAll2",method = RequestMethod.GET)
    public Object getAll2()
    {
        List<Channel> channelList = channelService.findAllRecord();
        List<ChannelCover2> channelCoverList = new ArrayList<ChannelCover2>();
        for(Channel channel : channelList){
            String geo1 = "无数据";
            String geo2 = "无数据";
            String geo3 = "无数据";
            if(channel.getGeo_id() != 0){
                GeoBuilding gA = geoBuildingService.findRecordById(channel.getGeo_id());
                if(gA == null) {
                    channelCoverList.add(new ChannelCover2(channel,geo1,geo2,geo3));
                    continue;
                }
                if(gA.getLevel() == 1) geo1 = gA.getName();
                if(gA.getLevel() == 2){
                    geo2 = gA.getName();
                    GeoBuilding gB = geoBuildingService.findRecordById(gA.getParent_id());
                    if(gB != null) {
                        geo1 = gB.getName();
                    }else{
                        channelCoverList.add(new ChannelCover2(channel,geo1,geo2,geo3));
                    }
                }
                if(gA.getLevel() == 3){
                    geo3 = gA.getName();
                    GeoBuilding gB = geoBuildingService.findRecordById(gA.getParent_id());
                    if(gB != null){
                        geo2 = gB.getName();
                        GeoBuilding gC = geoBuildingService.findRecordById(gB.getParent_id());
                        if(gC != null) {
                            geo1 = gC.getName();
                        }else{
                            channelCoverList.add(new ChannelCover2(channel,geo1,geo2,geo3));
                        }
                    }else{
                        channelCoverList.add(new ChannelCover2(channel,geo1,geo2,geo3));
                    }
                }
            }
            channelCoverList.add(new ChannelCover2(channel,geo1,geo2,geo3));
        }
        return MapRet.DATA(channelCoverList);
    }


    @RequestMapping(value = "/getChannelByName",method = RequestMethod.GET)
    public Object getChannelByName(@RequestParam(value = "name",required = true) String name)
    {
        List<Channel> channelList = channelService.findByName(name);
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        for(Channel channel: channelList){
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("id",channel.getId());
            map.put("text",channel.getChannel());
            mapList.add(map);
        }
        return MapRet.DATA(mapList);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object add(@RequestBody ChannelAdd channelAdd)
    {
       try {
           Channel channel = new Channel();
           Device device = deviceService.findAllById(channelAdd.getDevice_id());
           channel.setName(device.getDevice_name());
           channel.setIp(device.getDevice_ip());
           channel.setChannel(channelAdd.getChannel_number());
           channel.setType(channelAdd.getType_id());
           channel.setLow(channelAdd.getLow());
           channel.setHigh(channelAdd.getHigh());
           if(channelAdd.getType_id() == 0)
           {
               channel.setUnit("m(米)");
           }
           else
           {
               channel.setUnit("Mpa(兆帕)");
           }
           Channel channelOld = channelService.findByIPandChannel(new SelectIPandChannelCondition(channel.getIp(),channel.getChannel()));
           if(channelOld != null)
           {
               return MapRet.SQL_ERROR("数据已存在");
           }
           else{
               channelService.insertRecord(channel);
               GlobalChannel.setChannelList(channelService.findAllRecord());
               return MapRet.DATA(channelAdd);
           }
       }catch (Exception e)
       {
           e.printStackTrace();
           logger.error("添加通道数据错误：" + e);
           return MapRet.DATA_ERROR(e);
       }
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Object delete(@RequestParam(value = "id",required = true) int id)
    {
        try {

            Channel channel = channelService.findByID(id);
            Device oldDevice = new Device();
            oldDevice.setDevice_name(channel.getName());
            oldDevice.setDevice_ip(channel.getIp());
            Device device = deviceService.findAllByNameAndIp(oldDevice);
            if(device != null){
                MapPos mapPos = new MapPos();
                mapPos.setDevice_id(device.getId());
                mapPos.setCh_x(channel.getChannel());
                mapPosService.deleteByClass(mapPos);
            }
            channelService.deleteById(id);
            GlobalChannel.removeChannel(channel);
            return MapRet.SQL_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("删除通道数据错误：" + e);
            return MapRet.SQL_ERROR(e);
        }
    }

    @RequestMapping(value = "/updateChannel",method = RequestMethod.POST)
    public Object updateChannel(@RequestParam(value = "id",required = true) int id,
                                @RequestParam(value = "low",required = true) float low,
                                @RequestParam(value = "high",required = true) float high)
    {
        try {
            Channel channel = new Channel();
            channel.setId(id);
            channel.setLow(low);
            channel.setHigh(high);
            channelService.updateRecord(channel);
            GlobalChannel.setChannelList(channelService.findAllRecord());
            return MapRet.SQL_UPDATE_SUCCESS();
        }catch (Exception e){
            logger.error("更新通道上下限异常：" + e.getMessage());
            e.printStackTrace();
            return MapRet.SQL_UPDATE_ERROR();
        }
    }

}
